package minjre.binparse;

import minjre.utils.CommandUtils;
import minjre.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-05-28 15:39
 */
public class BinParse {
    private List<String> dllList;
    private File destFile;

    public BinParse(String outPath) {
        this.dllList = new ArrayList<>();
        dllList.add("java.exe");
        this.destFile = new File(outPath);
    }

    public void runParse(String pid, File binFile){
        // 获取Dll列表
        fillDllList(pid);
        // 遍历文件夹并复制
        copyBatchDll(binFile, destFile);
    }

    /**
     * 遍历并复制Dll文件
     * @param binSrc
     */
    private void copyBatchDll(File binSrc, File dest) {
        if(binSrc.isDirectory()){
            File[] files = binSrc.listFiles();
            dest = new File(dest, binSrc.getName());
            if(!dest.exists()){
                dest.mkdirs();
            }
            for (File file : files) {
                copyBatchDll(file, dest);
            }
        }else{
            if(hasDll(binSrc.getName())){
                FileUtils.copyFile(binSrc, new File(dest, binSrc.getName()));
            }
        }
    }

    /**
     * 判断是否存在该dll
     * @param name
     * @return
     */
    private boolean hasDll(String name) {
        for (String str : dllList) {
            if(str.toUpperCase().equals(name.toUpperCase())){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取Dll文件列表，填充list
     * @param pid
     */
    private void fillDllList(String pid){
        clearDllList();
        StringBuffer buffer = CommandUtils.doCommand("GBK",false,"tasklist", "/fi", "pid eq "+ pid, "/m");
        String loadFile = buffer.toString().split(pid)[1];
        for (String item : loadFile.split(",")) {
            dllList.add(item.trim());
        }
    }

    /**
     * 清空列表
     */
    public void clearDllList(){
        dllList.clear();
    }


    public List<String> getDllList() {
        return dllList;
    }

    public void setDllList(List<String> dllList) {
        this.dllList = dllList;
    }

}
